import 'dart:io';

import 'package:flutter_tts/flutter_tts.dart';

class TTSKit {
  static final TTSKit _instance = TTSKit();

  late FlutterTts flutterTts;
  String? language;
  String? engine;
  double volume = 0.5;
  double pitch = 1.0;
  double rate = 0.5;

  static TTSKit get instance {
    return _instance;
  }

  initTts() {
    flutterTts = FlutterTts();

    _setAwaitOptions();

    if (Platform.isAndroid) {
      _getDefaultEngine();
    }

    flutterTts.setStartHandler(() {
      print("Playing");
    });

    flutterTts.setCompletionHandler(() {
      print("Complete");
    });

    flutterTts.setCancelHandler(() {
      print("Cancel");
    });

    if (Platform.isIOS) {
      flutterTts.setPauseHandler(() {
        print("Paused");
      });

      flutterTts.setContinueHandler(() {
        print("Continued");
      });
    }

    flutterTts.setErrorHandler((msg) {
      print("error: $msg");
    });

  }

  Future<dynamic> _getLanguages() => flutterTts.getLanguages;

  Future<dynamic> _getEngines() => flutterTts.getEngines;

  Future _getDefaultEngine() async {
    var engine = await flutterTts.getDefaultEngine;
    if (engine != null) {
      print(engine);
    }
  }

  Future speak(String speechText) async {
    await flutterTts.setVolume(volume);
    await flutterTts.setSpeechRate(rate);
    await flutterTts.setPitch(pitch);
        // flutterTts.setEngine(engine)
    if (speechText.isNotEmpty) {
      await flutterTts.speak(speechText);
    }
  }

  Future _setAwaitOptions() async {
    await flutterTts.awaitSpeakCompletion(true);
  }

  Future stop() async {
    var result = await flutterTts.stop();
    // if (result == 1) setState(() => ttsState = TtsState.stopped);
  }

  Future pause() async {
    var result = await flutterTts.pause();
    // if (result == 1) setState(() => ttsState = TtsState.paused);
  }

  void dispose() {
    flutterTts.stop();
  }
}
